#include "TshEvent.h"

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/input.h>
#include <sys/epoll.h>
#include <string.h>
#include <sys/vfs.h>
#include <dirent.h>

TshEvent::TshEvent()
{
    inputEventDeal = NULL;
}

TshEvent::~TshEvent()
{

}


bool TshEvent::addAepollFile(const char* filename)
{
    bool re = false;
    int fd = open(filename, O_RDONLY | O_NONBLOCK);
    if (fd == -1 ) 
    {
        printf("open kd device or mouse fail!\n");
    }
    else 
    {
        ev.data.fd = fd;
        ev.events = EPOLLIN | EPOLLET;
        int i = epoll_ctl(m_epfd, EPOLL_CTL_ADD, fd, &ev);
        if (i == -1 ) 
        {
            printf("add %s device in epoll fail!\n", filename);
        }
        else 
        {
            printf("add %s device in epoll sucess!\n", filename);
            re = true;
        }
    }
    return re;
}

bool TshEvent::init()
{

    bool re = true;
    m_epfd = epoll_create(1);
    if (m_epfd == -1) 
    {
        printf("epoll create fail!\n");
    }

    return re;
}

void TshEvent::doInput(const epoll_event* ev)
{
    ssize_t resize = 0;
    ssize_t n = 0;
    struct tsh_event tsh_ev;
    while ((resize = read(ev->data.fd, buffer + n, sizeof(struct tsh_event))) > 0) 
    {
        n += resize;
        if (n == sizeof(tsh_event)) 
        {
             memcpy((void*)(&tsh_ev), buffer, sizeof(tsh_event));
             if( inputEventDeal != NULL )
             {
                inputEventDeal( tsh_ev.type, tsh_ev.code, tsh_ev.value);
             }

             n = 0;
         }
    }
}

void TshEvent::run()
{
    int re = 0;
    while (true) {
        re = epoll_wait(m_epfd, events, MAX_EVENTS, -1);
        for (int i = 0; i < re; ++i) 
        {
             if (events[i].events & EPOLLIN) 
             {
                doInput(events + i);
             }
        }
        re = 0;
    }
}

